<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <!-- <a-col :span="8">
            <a-form-model-item label="预计总工时(人/天)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expectTotalHours">
              <a-input-number v-model="model.expectTotalHours" :min="1" :max="999999999" :precision="2" style="width: 100%" />
            </a-form-model-item>
          </a-col> -->
          <!-- <a-col :span="8">
            <a-form-model-item label="是否选择模板" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isChoiseTemplate">
              <j-dict-select-tag @input="changeReadOnly" type="radio" v-model="model.isChoiseTemplate" dictCode="YES_OR_NO" placeholder="请选择是否选择模板" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="8" v-if="!readOnly">
            <a-form-model-item label="进度模板" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateId">
              <select-process-template-input :disabled="readOnly" v-model="model.templateId" placeholder="请选择进度模板" :multi="false" @input="getTemplateList" />
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <!-- <div style="margin-bottom: 6px;margin-top: 6px">
              <a-button @click="handleAdd" v-if="!formDisabled" type="primary">新增</a-button>
              <a-popconfirm
                v-if="!formDisabled && selectedRowKeys.length"
                style="margin-left: 20px;"
                placement="top"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete">
                <template slot="title">
                  <p>是否删除选中的列表？</p>
                </template>
                <a-button type="primary">删除</a-button>
              </a-popconfirm>
            </div> -->
            <a-table
              ref="table"
              size="middle"
              rowKey="id"
              :pagination="{
                pageSize: 15
              }"
              :loading="loading"
              :columns="columns1"
              :scroll="{y: tableHeight}"
              :data-source="dataSource">
              <!-- <span slot="action" slot-scope="text, record">

                <template v-if="!formDisabled">
                  <a-popover trigger="hover">
                    <template slot="content">
                      <p @click="handlerUp(text, record, index)" class="hover">向上移</p>
                      <p @click="handlerDown(text, record, index)" class="hover">向下移</p>
                      <p @click="addOne(text, record, index)" class="hover">插入一行</p>
                    </template>
                    <a-button icon="unordered-list" type="primary" :ghost="true" class="ruleButton">
                    </a-button>
                  </a-popover>
                  <a-divider type="vertical"/>
                  <a-button
                    class="ruleButton"
                    :ghost="true"
                    type="primary"
                    icon="edit"
                    @click="handleEdit(record)"/>
                  <a-divider type="vertical"/>
                  <a-popconfirm title="确定删除吗?" @confirm="() => unitDelete(record.id)">
                    <a-button
                      class="ruleButton"
                      :ghost="true"
                      type="primary"
                      icon="delete"
                    />
                  </a-popconfirm>
                </template>
              </span> -->
              <template slot="titleSlot" slot-scope="text">
                <span v-if="text">
                  {{ text }}%
                </span>
                <span v-if="!text">
                  -
                </span>
              </template>
            </a-table>
          </a-col>
        </a-row>
        <erp-progress-template-dt-modal ref="itemList" @ok="modalFormOk" :insertRows="insertRows"></erp-progress-template-dt-modal>
      </a-form-model>
    </j-form-container>
    <div style="height: 32px;"></div>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import SelectProcessTemplateInput from '@/views/scy/components/SelectProcessTemplateInput'
  import ErpProgressTemplateDtModal from './ErpProgressTemplateDtModal.vue'
  export default {
    name: 'ErpProgressTaskForm',
    components: {
      SelectProcessTemplateInput,
      ErpProgressTemplateDtModal
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        selectedRowKeys: [], // 选中的列表
        insertRows: null, // 插入的行
        model: {
          // isChoiseTemplate: '1'
        },
        readOnly: false,
        labelCol: {
        },
        validatorRules: {
        //   isChoiseTemplate: [
        //   { required: true, message: '请选择是否选择模板!' }
        // ],
        templateId: [
          { required: true, message: '请选择进度模板!' }
        ]
      },
        loading: false,
        columns: [
          {
            title: '顺序',
            dataIndex: '',
            key: 'rowIndex',
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          // {
          //   title: '操作',
          //   dataIndex: 'operation',
          //   align: 'center',
          //   scopedSlots: { customRender: 'operation' }
          // },
          {
            title: '节点名称',
            align: 'center',
            dataIndex: 'nodeName'
          },
          {
            title: '节点进度',
            align: 'center',
            dataIndex: 'nodeProgress',
            scopedSlots: { customRender: 'titleSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'action'
            }
          }
        ],
        columns1: [
          {
            title: '顺序',
            dataIndex: '',
            key: 'rowIndex',
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '节点名称',
            align: 'center',
            dataIndex: 'nodeName'
          },
          {
            title: '节点进度',
            align: 'center',
            dataIndex: 'nodeProgress',
            scopedSlots: { customRender: 'titleSlot' }
          }
        ],
        dataSource: [],
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        tableHeight: 0,
        url: {
          addTaskNode: '/api/erp/progress/erpProgressTask/addTaskNode',
          queryById: '/api/erp/progress/erpProgressTask/queryById',
          queryByMainId: '/api/erp/progress/erpProgressTaskNode/queryListByTaskId'
        }
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    mounted () {
      var that = this
      that.tableHeight = document.body.clientHeight - 400;
    },
    methods: {
      unitDelete(id) {
        for (let i = 0; i < this.dataSource.length; i++) {
          if (this.dataSource[i].id == id) {
            this.dataSource.splice(i, 1);
          }
        }
      },

      // 选中的列表
      onSelectChange (selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      },

      // 点击上移
      handlerUp (text, record, index) {
        console.log('------text, record, index--------', text, record, index)
        if (index == 0) {
          this.$message.warning('已在第一列了！')
          return false
        }
        let temp = this.dataSource[index - 1];
        this.$set(this.dataSource, index - 1, this.dataSource[index])
        this.$set(this.dataSource, index, temp)
      },
      // 点击下移
      handlerDown (text, record, index) {
        if (index == this.dataSource.length - 1) {
          this.$message.warning('已在最后一列了！')
          return false
        }
        let temp = this.dataSource[index + 1];
        this.$set(this.dataSource, index + 1, this.dataSource[index])
        this.$set(this.dataSource, index, temp)
      },

      // 点击插入一行
      addOne (text, record, index) {
        this.insertRows = index
        this.$refs.itemList.add();
        this.$refs.itemList.title = '节点新增';
        this.$refs.itemList.disableSubmit = false;
      },

      changeReadOnly(data) {
        this.dataSource = [] // 清空表格列表页
        this.model.templateId = ''
        if (data === '0') {
          this.readOnly = true
        } else {
          this.readOnly = false
        }
      },
      handleAdd() {
        this.$refs.itemList.add();
        this.$refs.itemList.title = '节点新增';
        this.$refs.itemList.disableSubmit = false;
        this.insertRows = null
      },
      // 点击批量删除
      handleDelete () {
        this.loading = true;
        console.log('-----selectedRowKeys', this.selectedRowKeys, this.dataSource)
        this.dataSource = this.dataSource.filter((item) => !this.selectedRowKeys.some(item2 => item2 == item.id))
        this.selectedRowKeys = []
        this.loading = false
      },
      handleEdit(record) {
        this.$refs.itemList.edit(record);
        this.$refs.itemList.title = '节点编辑';
        this.$refs.itemList.disableSubmit = false;
      },
      modalFormOk(data) {
        this.loading = true;
        let flag = true;
        // debugger;
        for (let i = 0; i < this.dataSource.length; i++) {
          console.log('------123123123', this.dataSource)
          if (this.dataSource[i].id == data.id) {
            console.log('------123123123')
            this.dataSource.splice(i, 1, data);
            flag = false;
          }
        }
        if (flag) {
          if (this.insertRows != null) {
            this.dataSource.splice(this.insertRows + 1, 0, data);
          } else {
            this.dataSource.push(data);
          }
        }
        this.loading = false;
      },
      getTemplateList(data, obj) {
        this.dataSource = data;
        // 后端无良心，需要前端自己处理，当选择了“允许添加子节点”需要在每一个节点里面塞isAddChildNode值最后一个节点不用塞
        let isAddChildNode = obj.isAddChildNode;
        data.forEach((item, index) => {
          if (index === data.length - 1) {
            item.isAddChildNode = '0';
          } else {
            item.isAddChildNode = isAddChildNode;
          }
        });
      },
      add() {
        this.edit(this.modelDefault);
      },
      edit(record) {
        this.dataSource = []
        this.model.isChoiseTemplate = '1'
        this.model = {};
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        if (!this.model.isChoiseTemplate) {
          this.model.isChoiseTemplate = '1'
          this.readOnly = false
        } else {
          if (this.model.isChoiseTemplate === '0') {
            this.readOnly = true
          }
        }
        if (this.model.id) {
          getAction(this.url.queryByMainId, { id: this.model.id }).then((res) => {
            if (res.success) {
              this.dataSource = res.result.records || res.result
            }
          })
        }
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.dataSource.length !== 0) {
              this.dataSource.forEach((val, index) => {
                console.log('index', index)
                console.log('val', val)
                if (!val.sortOrder) {
                  val.sortOrder = index + 1
                }
              })
            } else {
              that.$message.warning('请填写至少一条进度');
              return;
            }
            that.confirmLoading = true;
            let httpurl = this.url.addTaskNode;
            let method = 'post';
            this.model.nodeList = this.dataSource;
            this.model.saveStatus = 'yes' // 代表不是暂存
            httpAction(httpurl, this.model, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              this.dataSource = []
            })
          }
        })
      },

      TemporaryForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.dataSource.length !== 0) {
              this.dataSource.forEach((val, index) => {
                console.log('index', index)
                console.log('val', val)
                if (!val.sortOrder) {
                  val.sortOrder = index + 1
                }
              })
            } else {
              that.$message.warning('请填写至少一条进度');
              return;
            }
            that.confirmLoading = true;
            let httpurl = this.url.addTaskNode;
            let method = 'post';
            this.model.nodeList = this.dataSource;
            httpAction(httpurl, this.model, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              this.dataSource = []
            })
          }
        })
      }
    }
  }
</script>
<style scoped="scoped">
.hover{
  cursor: pointer;
}
.hover:hover{
  color: #1890ff;
}
</style>
